﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows;

namespace Update
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            string name = string.Empty;

            //启动参数处理
            if (e.Args.Length > 0)
            {
                name = e.Args[0];
            }
            if(name == string.Empty && ExecUpdate(name))
            {
                Application.Current.Shutdown(-1);
            }
            else
            {
                MainWindow ribbon = new MainWindow(name);
                ribbon.Show();
            }
        }

        private bool ExecUpdate(string path)
        {
            
            //更新程序复制到缓存文件夹
            // ReSharper disable PossiblyMistakenUseOfParamsMethod
            string appDir = Path.Combine(System.Reflection.Assembly.GetEntryAssembly().Location.Substring(0, System.Reflection.Assembly.GetEntryAssembly().Location.LastIndexOf(Path.DirectorySeparatorChar)));
            // ReSharper restore PossiblyMistakenUseOfParamsMethod
            if (appDir.EndsWith("UpdateCopy"))
                return false;

            string updateFileDir = Path.Combine(appDir, "UpdateCopy");

            if (!Directory.Exists(updateFileDir))
            {
                Directory.CreateDirectory(updateFileDir);
            }

           
            string exePath = Path.Combine(updateFileDir, "Update.exe");

            File.Copy(Path.Combine(appDir, "Update.exe"), exePath, true);
            StartExe(exePath,path, AppDomain.CurrentDomain.BaseDirectory);
            return true;
        }
        private void StartExe(string exeName, string arguments, string workingDirectory)
        {
            //声明一个程序信息类
            ProcessStartInfo info = new ProcessStartInfo
            {
                //设置外部程序名
                FileName = exeName,
                //设置外部程序的启动参数（命令行参数）为test.txt
                Arguments = arguments,
                //设置外部程序工作目录为  C:\
                WorkingDirectory = workingDirectory
            };

            try
            {
                //
                //启动外部程序
                //
                Process.Start(info);
            }
            catch (System.ComponentModel.Win32Exception e)
            {
                throw new Exception("系统找不到指定的程序文件。\r{0}", e);
            }
        }
    }
}
